import { defineStore } from "pinia";
import pinia from "@/store";
import { userLogin, refreshUerInfo } from "@/api/user";

export interface UserState {
    username: string;
    accessToken: string;
    refreshToken?: string;
    roles: Array<string>;
}

export type LoginRequest = {
    username: string;
    password: string;
}

export const userStoreHook = defineStore("userInfo", {
    state: (): UserState => {
        return {
            username: "zyh",
            accessToken: "",
            roles: ['common'],
        }
    },
    getters: {},
    actions: {
        storeUserLogin(data: LoginRequest) {
            return userLogin(data).then((res) => {
                this.username = res.username;
                this.roles = res.roles;
                this.accessToken = res.accessToken;
                return res;
            });
        },

        storeRefreshUserInfo() {
            if (this.username === 'zyh' && this.accessToken !== '') {
                refreshUerInfo({
                    accessToken: this.accessToken,
                }).then((res) => {
                    this.username = res.username;
                    this.roles = res.roles;
                    this.accessToken = res.accessToken;
                })
                    .catch((err) => {
                        console.log(err);
                        this.accessToken = '';
                    })
            }
        }
    },
    persist: {
        key: 'userInfo',
        storage:sessionStorage,
        paths: ['accessToken'],
    }
})

export function useUserStore(){
    return userStoreHook(pinia);
};
